<?php

function sales_invoice_stats_page()
{
    global $base_url;

    drupal_add_js('sites/all/libraries/echarts/echarts-all.js', array('type' => 'file'));
    drupal_add_js('sites/all/libraries/echarts/geoJson/china-main-city-map.js', array('type' => 'file'));
    drupal_add_js("var nonghuaBaseUrl = '$base_url';", array('type' => 'inline', 'scope' => 'footer'));
    drupal_add_js('sites/all/libraries/echarts/map.js', array('type' => 'file', 'scope' => 'footer'));
    drupal_add_js(drupal_get_path('module', 'sales') . '/js/sales.js', array('type' => 'file', 'scope' => 'footer'));
    drupal_add_js ( drupal_get_path ( 'module', 'nonghua_common' ) . '/jquery.url.js' );
    drupal_add_js ( drupal_get_path ( 'module', 'nonghua_common' ) . '/ajax.js' );
//    @$output = add_toggle_button();
//    $output .= add_map();
//    $output .= add_charts();
//    $output .= "<input id='invoiceStat' type='button' onclick='getSalesStats()' value='销售统计信息' class='btn btn-mini'>";
    @$output = drupal_render(drupal_get_form('sales_invoice_stats_form'));

    return $output;
}

function sales_invoice_stats_form($form, &$form_state)
{
    $form['national_id'] = array('#type' => 'hidden', '#default_value' => '');
    $form['geo_level'] = array('#type' => 'hidden', '#default_value' => '');
    $form['geo_name'] = array('#type' => 'hidden', '#default_value' => '');
    $form['map_or_zone'] = array('#type' => 'hidden', '#default_value' => 'map');
    $form['toggle-button']['#markup'] = add_toggle_button();
    $form['map']['#markup'] = add_map();
    $form['charts']['#markup'] = add_charts();
    /* 按区域查询 */
    $form['zone']['btn']['#markup']="<input id='invoiceStat' type='button' onclick='getSalesStats()' value='销售统计信息' class='btn btn-mini'>";
    $form['wrapper-zone']['#markup']='<div id="zone-wrapper-div">';
    $form['zone']['inner'] = _insert_salesman_distributor_selection_form($form, $form_state, 'zone','inner');
    $form['zone']['wrapper-zone-close']['#markup']="<input id='jurisinvoiceStat' type='button' onclick='getjurisSalesStats()' value='区域销售统计信息' class='btn btn-mini'>";
    


    $year_options['']='--年份--';
    for ($i = 0; $i < 5; $i++) {
        $year_options[date('Y')-$i] = date('Y')-$i;
    }
    $form['search']['wrapper']['#markup']='<div id="search-wrapper-div" style="clear:both;">';

//    $form['help']['#markup'] = _is_mobile()?"":'<div id="help"><a href="'.base_path().'" data-toggle="modal" target = "_blank">
//                                        <img src="'.base_path().'sites/all/themes/tweme/images/help.png"/>
//                                 </a></div>';
    $form['stats']['year'] = array(
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $year_options,
        '#default_value' => date('Y'),
    );

    $month_options['']='--月份--';
    for ($i = 1; $i < 13; $i++) {
        $month_options[$i] = $i;
    }
    $form['stats']['month'] = array(
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $month_options,
        '#default_value' => date('n'),
    );
    $form['stats']['search'] = array(
        '#type' => 'button',
        '#value' => t('查询'),
        '#ajax' => array(
            'callback' => 'search_callback',
            'wrapper' => 'search-wrapper-div',
            'method' => 'replace',
            'effect' => 'fade',

        ),
        '#validate' => array('check_year_not_empty', 'check_month_not_empty', 'check_geo_name_not_empty','check_zone_not_empty'),
    );
    $form['search']['table']['#markup'] = data_list_view_page($form_state);
    $form['search']['wrapper-close']['#markup']='</div>';
//    $form['search']['map_search']['#markup'] = "<input id='invoiceStat' type='button' onclick='getSalesStats()' value='销售统计信息' class='btn btn-mini'>";
//    $table['#markup'] = data_list_view_page( $form_state);
//    ajax_submit_form($form, $form_state, $table, '', array('check_year_not_empty', 'check_month_not_empty', 'check_geo_name_not_empty', 'check_zone_not_empty'));



    return $form;
}


function add_map()
{
    $output = '<div id="map-wrapper-div" class="clearfix">
                    <div id="divMap" class="divMapSize" ></div>
                    <input type="button" id="map_previous" value="上一级" class="btn btn-mini">
                    <input type="button" id="map_next" value="下一级" class="btn btn-mini">
               </div>';

    return $output;
}

function add_charts()
{
    // $output = '<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    //                 <div class="modal-header">
    //                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    //                     <h3 id="myModalLabel">销售统计信息 （环比）</h3>
    //                   </div>
    //                 <div id="divQoQ_sales" class="divLineChartSize"></div>
    //             </div>';
    //


         $output = '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
                   <div class="modal-dialog">
                      <div class="modal-content">
                         <div class="modal-header">
                            <button type="button" class="close"
                               data-dismiss="modal" aria-hidden="true">
                                  &times;
                            </button>
                            <h3 id="myModalLabel">销售统计信息 （环比）</h3>
                         </div>
                         <div id="divQoQ_sales" class="divLineChartSize"></div>
                      </div>
                    </div>
                </div>';
    return $output;
}


function add_toggle_button()
{
    $output = '<div class="btn-group btn-radio" data-toggle="buttons-radio">
             <button data-toggle="button" id="map" class="btn btn-small">地图</button>
             <button data-toggle="button" id="zone" class="btn btn-small">区域</button>
           </div>';
    return $output;
}

/**
 * Implements hook_validate().
 */
function sales_invoice_stats_form_validate($form, &$form_state)
{

}

function sales_invoice_stats_form_submit($form, &$form_state)
{

}

function check_year_not_empty($form, &$form_state)
{
     if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['year'])) {
        form_set_error('year', '年 不能为空');
    }
}

function check_month_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['month'])) {
        form_set_error('month', '月 不能为空');
    }
}

function check_geo_name_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'map' && empty($form_state['values']['geo_name'])) {
        form_set_error('', '未选中地理区域');
    }
}
function check_zone_not_empty($form, &$form_state)
{
    if ($form_state['values']['map_or_zone'] == 'zone' && empty($form_state['values']['juris'])) {
        form_set_error('', '未选中区域');
    }
}

function salesman_change_callback($form, &$form_state)
{
    return $form['zone']['juris'];
}

function data_list_view_page($form_state)
{
    $output = '';
//    $res_img = _is_mobile()?"":"<img src='".base_path()."sites/all/themes/tweme/images/result.png'>";
//    $output .="<div class='table-div'>$res_img<div class='table-border-div'>";
    //表头
    $header = array(
        array('data' => '发票id号', 'class' => ['integrant essential break no'], 'field' => 'invoice_id'),
        array('data' => '日期', 'class' => ['integrant essential date'], 'field' => 'invoice_date'),
        array('data' => '销售员', 'class' => ['essential salesman']),
        array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '销售类型', 'class' => ['essential sales_type_name']),
        array('data' => '化肥品种', 'class' => ['essential sacfvariety']),
        array('data' => '配比', 'class' => 'optional proportion'),
        array('data' => 'SM', 'class' => 'optional SM'),
        array('data' => '数量', 'class' => ['integrant essential quantity'], 'field' => 'quantity'),
        array('data' => '省', 'class' => ['optional province']),
        array('data' => '市', 'class' => ['optional city']),
        array('data' => '县', 'class' => ['optional county']),
        array('data' => '火车站名', 'class' => ['optional station_name']),
        array('data' => '关内/关外', 'class' => ['integrant optional inorout'], 'field' => 'inorout'),
    );

    $geo_level = $form_state['values']['geo_level'];
    if ($geo_level == '1') {
        $join_column = 'province_id';
    } else if ($geo_level == '2') {
        $join_column = 'city_id';
    } else if ($geo_level == '3') {
        $join_column = 'county_id';
    } else if ($geo_level == '4') {
        $join_column = 'town_id';
    } else {
        $join_column = 'village_id';
    }
    // if($form_state['triggering_element']['#value'] == '查询'){

        $map_or_zone = $form_state['values']['map_or_zone'];
        $juris = $form_state['values']['juris'];
        $salesman = $form_state['values']['salesman'];
        $distributor = $form_state['values']['distributor'];
        $national_id = $form_state['values']['national_id'];

        $query = db_select('invoice', 'I')->extend('PagerDefault')->extend('TableSort');
        $query->leftjoin('users', 'U', 'U.uid=I.author_uid');
        $query->join('employee', 'E', 'E.employee_id=I.salesman_id');
        $query->join('distributor', 'D', 'D.distributor_id=I.distributor_id');
        $query->join('sales_type', 'ST', 'ST.sales_type_id=I.sales_type_id');
        $query->join('product_sku', 'SV', 'SV.product_sku_id=I.sacfvariety_id');

        $query->addField('D', 'distributor_name');
        if ($map_or_zone == 'map') {
            $query->join('addr', 'A1', 'A1.addr_id=D.addr_id');
            if ($geo_level <= 2) {
                $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
            } else {
                $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
                $query->join('addr', 'A3', "A3.addr_id=A2.pid");
            }
        } else {
            if (!empty($distributor)) {
                // join nothing
            } else if (!empty($salesman)) {
                //join nothing
            } else if (!empty($juris)) {
                $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
                $query->join('employee', 'EE', 'EE.employee_id = SD.salesman_id');
            }
        }

        $query->leftJoin('addr', 'A', 'A.addr_id=I.delivery_addr_id');
        $query->leftJoin('addr', 'A7', 'A.province_id=A7.addr_id');
        $query->leftJoin('addr', 'A8', 'A.city_id=A8.addr_id');
        $query->leftJoin('addr', 'A9', 'A.county_id=A9.addr_id');

        if ($map_or_zone == 'map') {
            if ($geo_level <= 2) {
                $query->condition('A2.national_id', $national_id);
            } else {
                $query->condition('A3.national_id', $national_id);
                $query->condition('A2.name', $form_state['values']['geo_name']);
            }
        } else {
            if (!empty($distributor)) {
                $query->condition('D.distributor_id', $distributor);
            } else if (!empty($salesman)) {

                $query->condition('I.salesman_id', $salesman);
            } else if (!empty($juris)) {
                $query->condition('EE.juris_id', $juris);
            }
        }
        $datestr = '';
        if (!empty($form_state['values']['year'])) {//查询条件
            if ($form_state['values']['year']) {
                $datestr .= $form_state['values']['year'] . '-';
            }
        }
        if (!empty($form_state['values']['month'])) {//查询条件
            if ($month = $form_state['values']['month']) {
                if ($month < 10)
                    $datestr .= '0' . $form_state['values']['month'];
                else
                    $datestr .= $form_state['values']['month'];
            }
        }
        if ($datestr) {
            $query->condition('I.invoice_date', db_like($datestr) . '%', 'LIKE');
        }
        $query->addField('A7', 'name', 'province');
        $query->addField('A8', 'name', 'city');
        $query->addField('A9', 'name', 'county');
        $query->fields('I');
        $query->addField('E', 'employee_name', 'salesman');
        $query->addField('ST', 'sales_type_name');
        $query->addField('SV', 'variety_name');
        $query->addField('SV', 'proportion');
        $query->addField('SV', 'SM');
        if($form_state['triggering_element']['#value'] != '查询')
            $query->orderBy('I.timestamp', 'DESC');
        $query->limit(variable_get("list_page_item_number", 5));
        $invoiceInfo = $query->orderByHeader($header)->execute();
        $rows = array();
        //表内容
        $n = 1;
        foreach ($invoiceInfo as $row) {
            $rows[] = array(
                array('data' => $row->invoice_id, 'class' => ['essential break invoice_id']),
                array('data' => $row->invoice_date, 'class' => ['essential date']),
                array('data' => $row->salesman, 'class' => ['essential salesman']),//
                array('data' => '<a href="'.base_path().'distributor/edit/' . $row->distributor_id . '" data-toggle="modal" target = "_blank">'.$row->distributor_name.'</a>', 'class' => ['integrant essential distributor']),
                array('data' => $row->sales_type_name, 'class' => ['essential sales_type_name']),
                array('data' => $row->variety_name, 'class' => ['integrant essential sacfvariety']),
                array('data' => $row->proportion, 'class' => 'optional proportion'),
                array('data' => $row->SM, 'class' => 'optional SM'),
                array('data' => $row->quantity, 'class' => ['essential quantity']),
                array('data' => $row->province, 'class' => ['integrant optional province']),
                array('data' => $row->city, 'class' => ['integrant optional city']),
                array('data' => $row->county, 'class' => ['optional county']),
                array('data' => $row->station_name, 'class' => ['optional station_name']),
                array('data' => $row->inorout, 'class' => ['optional inorout']),
            );
        }
    // }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced'))));
    $output .= theme('pager');
//    $output .='</div></div>';
    return $output;
}

function search_callback($form, &$form_state)
{
    return $form['search'];
}